<?php
if (!defined('BASEPATH')) exit('no direct script access allowd');

class MY_Form_validation extends CI_Form_validation{
    
	public function __construct(){
        parent::__construct();
		$this->_error_prefix = '';
		$this->_error_suffix = '';
	}
	
	// 汉字、数字、字母组合、区分大小写
	public function cor_char($str){
		return (! preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9]+$/u", $str)) ? false : true;
	}
	
	// 至少多少位
	public function str_minlen($str, $val){
		if(! is_numeric($val)){
			return false;
		}
		return strlen($str) >= $val*3;
	}
	
	// 最大多少位
	public function str_maxlen($str, $val){
		if(! is_numeric($val)){
			return false;
		}
		return strlen($str) <= $val*3;
	}
	
	// 手机号码
	public function valid_phone($str){
		return (bool) preg_match("/^1[3456789]{1}\d{9}$/ix", $str);
	}
	
	// 身份证号
	public function valid_idcard($number){
		$number = strtoupper($number);
		if(! preg_match("/(^\d{15}$)|(^\d{17}([0-9]|X)$)/", $number)){
			return false;
		}
		$numlen = strlen($number);
		if(15 == $numlen){
			$birthday = substr($number, 6, 6);
			$bth_year = '19' . substr($birthday, 0, 2);
			$bth_month = substr($birthday, 2, 2);
			$bth_day = substr($birthday, 4, 2);
		}else{
			$birthday = substr($number, 6, 8);
			$bth_year = substr($birthday, 0, 4);
			$bth_month = substr($birthday, 4, 2);
			$bth_day = substr($birthday, 6, 2);
		}
		if($bth_year < 1900 || $bth_year > date('Y') || $bth_month < 1 || $bth_month > 12 || $bth_day < 1 || $bth_day > 31){
			return false;
		}
		if(18 == $numlen){
			$sigma = 0;
			//加权因子 
			$wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
			//校验码串 
			$ai = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
			//按顺序循环处理前17位 
			for ($i = 0;$i < 17;$i++) {
				//提取前17位的其中一位，并将变量类型转为实数 
				$b = (int) $number{$i}; 
				//提取相应的加权因子 
				$w = $wi[$i];
				//把从身份证号码中提取的一位数字和加权因子相乘，并累加 得到身份证前17位的乘机的和 
				$sigma += $b * $w;
			}
			$snumber = $sigma % 11;
			$check_number = $ai[$snumber];
			if($number{17} != $check_number) {
				return false;
			}
		}
		return true;
	}
	
	// 正整数
	public function pos_int($str){
		return (bool) preg_match('/^[1-9]\d*$/', $str);
	}
	
	// 负整数
	public function neg_int($str){
		return (bool) preg_match('/^[\-][1-9]\d*$/', $str);
	}
	
	// 返回验证错误信息数组
	public function error_array(){
		if (count($this->_error_array) === 0){
			return array();
		}
		return $this->_error_array;
	}
	
}